package com.hnx.admin.common.security.utils;

import jakarta.servlet.http.HttpServletRequest;

import java.util.Map;

/*
创建人： 倔强的头发
创建时间：2024/7/10
功能描述:

*/
public class RequestContextHolderUtil {
    private static final ThreadLocal<String> requestIdHolder = new ThreadLocal<>();
    private static final ThreadLocal<Map<String,Object>> contextHolder = new ThreadLocal<>();
    private static final ThreadLocal<HttpServletRequest> requestHolder = new ThreadLocal<>();
    public static void setRequestId(String requestId) {
        requestIdHolder.set(requestId);
    }

    public static String getRequestId() {
        return requestIdHolder.get();
    }
    public static HttpServletRequest getRequest(){
        return requestHolder.get();
    }
    public static void setRequest(HttpServletRequest request){
        requestHolder.set(request);
    }
    public static void setContext(Map<String,Object> context) {
        contextHolder.set(context);
    }

    public static Map<String,Object> getContext() {
        return contextHolder.get();
    }
    public static void clear() {
        contextHolder.remove();
        requestHolder.remove();
        requestIdHolder.remove();
    }
    public static String generateRequestId() {
        return cn.hutool.core.lang.UUID.fastUUID().toString(true);
    }
    public static String getRequestId(HttpServletRequest request) {
        String requestId = request.getHeader("requestId");
        if (requestId == null) {
            requestId = generateRequestId();
        }
        return requestId;
    }
    /**
     * 从请求上下文中提取用户名。
     * @param login 请求上下文中的登录信息
     * @return 提取的用户名或null（如果提取失败或用户名不存在）
     */
    public static String extractUsername(Map<String, Object> login,String usernameKey) {
        if (login == null) {
            return null;
        }
        Object rawUsername = login.get(usernameKey);
        // 检查获取的用户名是否为字符串类型
        if (rawUsername instanceof String) {
            return (String) rawUsername;
        } else if (rawUsername != null) {
            // 如果不是字符串类型，则记录错误或进行适当的处理
            throw new RuntimeException("Username is not of type String.");
        }
        // 如果用户名为null或不是字符串类型，则返回null
        return null;
    }
}
